package com.qdl.rym.util.config;

import com.aliyun.oss.OSSClient;
import com.qdl.rym.exception.BusinessException;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @Description: UploadConfig 上传文件的配置设置
 * @Author: ChenXueLi
 * @Date: 2019-02-12 16:37
 * 你是一段成熟的代码，要学会自己改bug
 */
@Data
public class UploadConfig {

    /**
     * 上传的文件名称
     */
    private String fileName;

    /**
     * 上传的文件名称（原名称）
     */
    private String oldFileName;

    /**
     * 上传的文件类型
     */
    private String fileType;

    /**
     * 是否随机名称
     */
    private boolean randomName;

    /**
     * 保存到的位置
     */
    private String folder;

    /**
     * 保存的位置是否要防盗链
     */
    private boolean chain;

    /**
     * 访问网络 true内网 false外网
     */
    private boolean internal;

    /**
     * 文件长度
     */
    private long fileSize;

    private String endPoint = "oss-cn-hangzhou.aliyuncs.com";
    private String endPointInternal = "oss-cn-hangzhou.aliyuncs.com";
    private String bucket = "chenxueli";
    private String bucketNoChain = "chenxueli";
    private String accessKeyId = "LTAI9M7M4PhiSjqW";
    private String accessKeySecret = "cOYcuk2OPHV5Z2pUn1YZtiMN9Vx2BF";

    public OSSClient getOSSClient() {
        String endPoint = this.endPoint;
        String bucket = this.bucket;
        String accessKeyId = this.accessKeyId;
        String accessKeySecret = this.accessKeySecret;
        if (chain) {
            bucket = this.bucketNoChain;
        }
        if (internal) {
            endPoint = this.endPointInternal;
        }
        return new OSSClient(endPoint, accessKeyId, accessKeySecret);
    }

    public InputStream getInputStream(MultipartFile multipartFile) {
        try {
            this.fileSize = multipartFile.getSize();
            this.oldFileName = multipartFile.getOriginalFilename();
            return multipartFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(-1001, "文件信息获取错误");
        }
    }

    public InputStream getInputStream(File file) {
        try {
            this.fileSize = file.length();
            this.oldFileName = file.getName();
            return new FileInputStream(file);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException(-1001, "文件信息获取错误");
        }
    }

}
